/*
 * Author: Hung Tran
*/
package viettravel.guiandevent.place;

import java.util.ArrayList;

import org.holoeverywhere.app.AlertDialog;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import viettravel.DAO.PlaceDAO;
import viettravel.DTO.ViettravelDTO;
import viettravel.common.Constants;
import viettravel.guiandevent.R;
import android.app.SearchManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.MenuItem.OnMenuItemClickListener;
import com.actionbarsherlock.view.SubMenu;
import com.actionbarsherlock.widget.SearchView;

public class ListPlaceFavorite extends SherlockActivity implements
		SearchView.OnQueryTextListener, 
		SearchView.OnCloseListener{
	
    private ListView mListPlace;
    private ArrayList<PlaceDAO> mListRowPlace;
    private ListPlaceAdapter mListPlaceAdapter;
    private ArrayList<Integer> mListPlaceId;
    private boolean isAscending = false;
    private int mCurrentPlaceID;
    @SuppressWarnings("unused")
	private String mUserID;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setTheme(Constants.THEME);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_list_place);
              
		ActionBar actionBar = getSupportActionBar();
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
		actionBar.setDisplayHomeAsUpEnabled(false);
		actionBar.setHomeButtonEnabled(true);
		actionBar.setIcon(R.drawable.ic_back_arrow);
		actionBar.setTitle(R.string.msgfavoritheader);
		actionBar.setBackgroundDrawable(Constants.APP_DRAWABLE);
        mListPlace = (ListView)findViewById(R.id.listPlace);
        mListPlaceId=new ArrayList<Integer>();
        
        Bundle extra=getIntent().getExtras();
        if (extra!=null){
        	JSONObject json;
        	try {
        		json=new JSONObject(extra.getString("FAVORITE"));
        		if(json !=null){
        			JSONArray array=json.getJSONArray(Constants.TAG_PLACES);
        			for (int i = 0; i < array.length(); i++) {
						mListPlaceId.add(array.getInt(i));
					}
        		}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }
        mListPlace.setOnItemClickListener(listPlaceOnClickListener);
        mListPlace.setOnItemLongClickListener(listPlaceFavoriteOnItemLongClickListener);
        
        mUserID = Constants.CURRENT_FACEBOOK_USER.getId();
        mListRowPlace = new ArrayList<PlaceDAO>();
        
        /*
         * Query database to GUI
         */
        ViettravelDTO mViettravelDTO = ViettravelDTO.getInstance();
        for(int i = 0; i < mListPlaceId.size(); i++){
        	mListRowPlace.add(mViettravelDTO.findPlaceById(mListPlaceId.get(i)));
        	Log.v(Constants.TAG, mListPlaceId.get(i)+"");
        }
        /*mListRowPlace = mViettravelBLL.getListFavorit();*/
        mListPlaceAdapter = new ListPlaceAdapter(mListRowPlace, this);
        if(isAscending)
        	mListPlaceAdapter.ascSort();
        else
        	mListPlaceAdapter.decSort();
        mListPlace.setAdapter(mListPlaceAdapter);   
    }
    
    //ListPlace detail
    OnItemClickListener listPlaceOnClickListener = new OnItemClickListener() {
    	@Override
		public void onItemClick(AdapterView<?> _adapterView, View _view, int _position,
				long _viewId) {
			PlaceDAO r = (PlaceDAO) mListPlaceAdapter.getItem(_position);
			Intent intent = new Intent(ListPlaceFavorite.this, PlaceDetail.class);
			intent.putExtra(Constants.EXTRA_PLACE_ID, r.getId());
			startActivity(intent);
		}
	};
	
	OnItemLongClickListener listPlaceFavoriteOnItemLongClickListener = new OnItemLongClickListener() {
		@SuppressWarnings("deprecation")
		@Override
		public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
				final int position, long arg3) {
			AlertDialog alertDialog = new AlertDialog.Builder(
					ListPlaceFavorite.this, AlertDialog.THEME_HOLO_LIGHT)
					.create();
			alertDialog
					.setTitle(getString(R.string.msgfavoriteremovedialogtitle));
			alertDialog
					.setMessage(getString(R.string.msgfavorite_removedialog_message));
			alertDialog.setButton(
					getString(R.string.msgfavorite_removedialog_ok),
					new DialogInterface.OnClickListener() {
						public void onClick(final DialogInterface dialog,
								final int which) {
							mCurrentPlaceID = mListRowPlace.get(position).getId();
							Log.v(Constants.TAG, Constants.CURRENT_FACEBOOK_USER.getName());
							Log.v(Constants.TAG, mCurrentPlaceID + "");
							Log.v(Constants.TAG, mListRowPlace.get(position)
									.getPlaceName());
						}
					});
			alertDialog.setIcon(R.drawable.abs__ic_clear_normal);
			alertDialog.show();

			return false;
		}
	};

	@Override
	public boolean onCreateOptionsMenu(Menu _menu) {

		SearchView mSearchView = new SearchView(getSupportActionBar()
				.getThemedContext());
		mSearchView.setQueryHint("Search...");
		SearchManager searchManager = (SearchManager) this
				.getSystemService(Context.SEARCH_SERVICE);
		mSearchView.setSearchableInfo(searchManager.getSearchableInfo(this
				.getComponentName()));
		mSearchView.setIconifiedByDefault(false);
		mSearchView.setOnQueryTextListener(this);
		mSearchView.setOnCloseListener(this);

		_menu.add("Search")
				.setIcon(R.drawable.abs__ic_search)
				.setActionView(mSearchView)
				.setShowAsAction(
						MenuItem.SHOW_AS_ACTION_IF_ROOM
								| MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);

		SubMenu subMenuSort = _menu.addSubMenu(this.getString(R.string.submenu_control));
		subMenuSort.add(this.getString(R.string.sort_asc_vote)).setOnMenuItemClickListener(new OnMenuItemClickListener() {
			@Override
			public boolean onMenuItemClick(MenuItem item) {
				mListPlaceAdapter.ascSort();
				isAscending = true;
				return false;
			}
		});
		
		subMenuSort.add(this.getString(R.string.sort_desc_vote)).setOnMenuItemClickListener(new OnMenuItemClickListener() {
			@Override
			public boolean onMenuItemClick(MenuItem item) {
				mListPlaceAdapter.decSort();
				isAscending = false;
				return false;
			}
		});;
		
		MenuItem menuItemSort = subMenuSort.getItem();
		menuItemSort.setIcon(R.drawable.ic_list_w);
		menuItemSort.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
        return super.onCreateOptionsMenu(_menu);
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case android.R.id.home:{
			finish();
            return true;
		}
		default:
			return super.onMenuItemSelected(featureId, item);
		}
	}

	@Override
	public boolean onClose() {
		// TODO Auto-generated method stub
		mListPlaceAdapter.filterData("");
		finish();
		finish();
		return false;
	}

	@Override
	public boolean onQueryTextSubmit(String _query) {
		mListPlaceAdapter.filterData(_query);
		return false;
	}

	@Override
	public boolean onQueryTextChange(String _query) {
		mListPlaceAdapter.filterData(_query);
		return false;
	}
}
